<template>
    <a-layout>
        <a-layout-content
                :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
        >
            <a-row :gutter="24">
                <a-col :span="8">
                    <p>
                        <a-form layout="inline" :model="param">
                            <a-form-item>
                                <a-button type="primary" @click="add">
                                    新增
                                </a-button>
                            </a-form-item>
                        </a-form>
                    </p>
                    <a-table
                            v-if="level1.length > 0"
                            :columns="columns"
                            :row-key="record=>record.id"
                            :data-source="level1"
                            :pagination="false"
                            :loading="loading"
                            size="small"
                            :defaultExpandAllRows="true"
                    >
                        <template v-slot:name="{ text,record }">
                            {{record.sort}} {{text}}
                        </template>
                        <template v-slot:action="{text,record}">
                            <a-space size="small">
                                <a-button type="primary" size="small" @click="edit(record)">编辑</a-button>
                                <a-popconfirm
                                        title="该文档将被永久删除无法回复，是否确认删除?"
                                        ok-text="是"
                                        cancel-text="否"
                                        @confirm="showConfirm(record.id)"
                                >
                                    <a-button type="danger" size="small">删除</a-button>
                                </a-popconfirm>
                            </a-space>
                        </template>
                    </a-table>
                </a-col>
                <a-col :span="16">
                    <p>
                        <a-form layout="inline" :model="param">
                            <a-button type="primary" @click="handleSave">保存</a-button>
                        </a-form>
                    </p>
                    <a-form :model="doc" layout="vertical">
                        <a-form-item>
                            <a-input v-model:value="doc.name" placeholder="名称"/>
                        </a-form-item>
                        <a-form-item>
                            <a-tree-select
                                    v-model:value="doc.parent"
                                    style="width: 100%"
                                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                    :tree-data="treeSelectData"
                                    tree-default-expand-all
                                    :replaceFields="{title:'name',key:'id',value:'id'}"
                                    placeholder="父分类"
                            >
                            </a-tree-select>
                        </a-form-item>
                        <a-form-item>
                            <a-input v-model:value="doc.sort" placeholder="顺序"/>
                        </a-form-item>
                        <a-form-item>
                            <a-button type="primary" @click="handlePreviewContent">
                                <EyeOutlined/>
                                内容预览
                            </a-button>
                        </a-form-item>
                        <a-form-item>
                            <div id="content"></div>
                        </a-form-item>
                    </a-form>
                </a-col>
            </a-row>
            <a-drawer
                    width="70%"
                    placement="right"
                    :closable="false"
                    v-model:visible="drawerVisible"
                    @close="onDrawerClose"
            >
                <div class="wangeditor" :innerHTML="previewHtml"></div>
            </a-drawer>
        </a-layout-content>
    </a-layout>
    <!--    <a-modal-->
    <!--            title="文档表单"-->
    <!--            v-model:visible="modelVisible"-->
    <!--            :confirm-loading="modelLoading"-->
    <!--            @ok="handleSave"-->
    <!--    >-->
    <!--    </a-modal>-->
</template>

<script lang="ts">
    import {createVNode, defineComponent, onMounted, ref} from 'vue';
    import Axios from "axios";
    import {message, Modal} from "ant-design-vue";
    import {Tool} from "@/util/util";
    import {useRoute} from "vue-router";
    import {ExclamationCircleOutlined} from '@ant-design/icons-vue';
    import E from 'wangeditor'

    export default defineComponent({

        name: 'AdminDoc',
        setup() {

            /**
             *搜索框参数
             */
            const param = ref();
            param.value = {};
            const docs = ref();

            const loading = ref(false);

            const route = useRoute();

            const treeSelectData = ref();
            treeSelectData.value = [];

            const setDisable = (treeSelectData: any, id: any) => {
                for (let i = 0; i < treeSelectData.length; i++) {
                    const node = treeSelectData[i];
                    if (node.id === id) {
                        node.disabled = true;

                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            for (let j = 0; j < children.length; j++) {
                                setDisable(children, children[j].id)
                            }
                        }
                    } else {
                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            setDisable(children, id)
                        }
                    }
                }
            };

            /**
             *表格渲染
             */
            const columns = [
                {
                    title: '名称',
                    dataIndex: 'name',
                    slots: {customRender: 'name'}
                },
                {
                    title: '操作',
                    key: 'action',
                    slots: {customRender: 'action'},
                },
            ];

            const level1 = ref();
            level1.value = [];

            /**
             * 数据查询
             */
            const handleQuery = () => {
                loading.value = true;
                level1.value = [];
                Axios.get("/doc/all/" + route.query.ebookId).then(response => {
                    loading.value = false;
                    const data = response.data;
                    if (data.success) {
                        docs.value = data.content;
                        level1.value = [];
                        level1.value = Tool.array2Tree(docs.value, 0);
                        console.log(level1)
                        treeSelectData.value = Tool.copy(level1.value) || [];
                        treeSelectData.value.unshift({id: 0, name: '无'});
                    } else {
                        message.error(data.message);
                    }
                });
            };

            /**
             * 表单
             */

            const doc = ref();
            doc.value = {ebookId: route.query.ebookId};
            const modelVisible = ref(false);
            const modelLoading = ref(false);
            const editor = new E('#content');
            editor.config.zIndex = 0;

            const handleSave = () => {
                modelLoading.value = true;
                doc.value.content = editor.txt.html();
                Axios.post("/doc/save", doc.value).then(response => {
                    modelLoading.value = false;
                    const data = response.data;
                    if (data.success) {
                        message.success("保存成功");
                        handleQuery()
                    } else {
                        message.error(data.message)
                    }
                });
            };


            /**
             * 编辑
             */
            const edit = (record: any) => {
                editor.txt.html("");
                modelVisible.value = true;
                doc.value = Tool.copy(record);
                handleQueryContent();
                treeSelectData.value = Tool.copy(level1.value);
                setDisable(treeSelectData.value, record.id);

                treeSelectData.value.unshift({id: 0, name: '无'});
                console.log("树形：", treeSelectData.value)
                editor.create();
            };

            /**
             * 新增
             */
            const add = () => {
                // 清空富文本框
                editor.txt.html("");
                modelVisible.value = true;
                doc.value = {ebookId: route.query.ebookId};

                treeSelectData.value = Tool.copy(level1.value) || [];

                // 为选择树添加一个"无"
                treeSelectData.value.unshift({id: 0, name: '无'});
            };

            /**
             * 内容查询
             */
            const handleQueryContent = () => {
                Axios.get("/doc/find-content/" + doc.value.id).then(response => {
                    const data = response.data;
                    if (data.success) {
                        editor.txt.html(data.content)
                    } else {
                        message.error(data.message);
                    }
                });
            };

            let ids: Array<string> = [];
            let names: Array<string> = [];

            const getDeleteIds = (treeSelectData: any, id: any) => {
                for (let i = 0; i < treeSelectData.length; i++) {
                    const node = treeSelectData[i];
                    if (node.id === id) {
                        ids.push(node.id)
                        names.push(node.name)
                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            for (let j = 0; j < children.length; j++) {
                                getDeleteIds(children, children[j].id)
                            }
                        }
                    } else {
                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            getDeleteIds(children, id)
                        }
                    }
                }
            };

            /**
             * 删除
             */
            const handleDelete = (id: number) => {
                Axios.delete("/doc/delete/" + ids.join(',')).then(response => {
                    const data = response.data;
                    if (data.success) {
                        handleQuery()
                        ids.length = 0;
                        names.length = 0;
                    }
                });
            };

            const showConfirm = (id: any) => {
                getDeleteIds(level1.value, id);
                Modal.confirm({
                    title: '你确定要删除文档?',
                    icon: createVNode(ExclamationCircleOutlined),
                    content: createVNode('div', {style: 'color:blue;'}, '文档为' + '【' + names.join('  ') + '】'),
                    okType: 'danger',
                    okText: '确认',
                    cancelText: '取消',
                    onOk() {
                        handleDelete(id);
                    },
                    onCancel() {
                        ids.length = 0;
                        names.length = 0;
                    },
                });
            };

            /**
             * 富文本预览
             */
            const drawerVisible = ref(false);
            const previewHtml = ref();
            const handlePreviewContent = () => {
                const html = editor.txt.html();
                previewHtml.value = html;
                drawerVisible.value = true;
            };
            const onDrawerClose = () => {
                drawerVisible.value = false;
            }

            onMounted(() => {
                handleQuery();
                editor.create()
            });

            return {
                param,
                //docs,
                level1,
                columns,
                loading,
                treeSelectData,

                edit,
                add,
                handleDelete,
                handleQuery,

                doc,
                modelVisible,
                modelLoading,
                handleSave,
                showConfirm,

                drawerVisible,
                previewHtml,
                handlePreviewContent,
                onDrawerClose
            };
        },
    });
</script>
